/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-07-13 09:26:36
 * @LastEditors: cuidm
 * @LastEditTime: 2022-10-21 12:01:09
 */

import React, { useEffect, useState } from "react";
import { Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Tree, message, Spin, Empty } from "antd";
import { EyeOutlined, EyeInvisibleOutlined } from "@ant-design/icons";
import { TempImportModal} from "@/components";
import request, { exportFile } from "@/utils/request";
import cmdbres from "@/data/cmdbres";
import hcpUtils from '@/utils/hcpUtils';
import "./index.less";

const {TreeNode} = Tree;
const ModelTree = ({ history, match, location, moduleId, onView }) => {
    const [loading, setLoading] = useState(true);
    const [treeData, setTreeData] = useState([]);
    
    const renderTitle = (item) => {
        return (
            <>
                <span className="node-name" title={item.name}>{item.name}</span>
                <span className="opt-btn">
                {
                    item.disabled ? 
                    <EyeInvisibleOutlined className="icon show" onClick={() => {onChangeView(item, false)}} />
                    :<>
                        {item.moduleNumber !== undefined && <span className="num">{item.moduleNumber}</span>} 
                        <EyeOutlined className="icon" onClick={() => {onChangeView(item, true)}} /> 
                    </>
                }
                </span>
            </>
        )
    }

    const queryModel = async () => {
        try {
            setLoading(true);
            let res = await request({
                ...cmdbres.queryModelList,
                params: {
                    namespace: "default",
                },
            });
            
            if (res && res.code == 200) {
                let moduleIcons = {};
                const treeDataIteration = (data) => {
                    let moduleNumber = 0;
                    data.map(item => {
                        let num = 0;
                        if(item.cmModuleId) { //是模型
                            item.key = item.cmModuleId;
                            item.name = item.moduleName;
                            item.icon = <span className={`iconfont ${item.moduleIcon}`}></span>;
                            item.type = "module";
                            item.parentKey = item.moduleClassificationId;
                            moduleIcons[item.cmModuleId] = item.moduleIcon;
                        } else { //是分组
                            item.key = item.id;
                            item.name = item.moduleClassificationName;
                            item.type = item.parentId ? "secondary" : "top";//顶级和次级分组
                            if(!(item.definitions && item.children)) {
                                item.switcherIcon = null;
                            }
                            item.parentKey = item.parentId || 0;
                            item.icon = null;
                            num += item.definitions?.length??0;
                        }
    
                        if(item.definitions && item.definitions.length) {
                            item.children = item.children ? item.children.concat(item.definitions) : item.definitions;
                            delete item.definitions; 
                        }
                        item.displayName = item.name;
                        item.disabled = false;
                      if(item.children) {
                        num += treeDataIteration(item.children);
                        moduleNumber += num;
                      }
                      item.moduleNumber = num;
                      item.title = renderTitle(item);
                    });
                    return moduleNumber;
                  };
                const arr = [{
                    id: 'all',
                    moduleClassificationName: '全部模型',
                    children: res.data
                }];
                treeDataIteration(arr);
                setTreeData(arr);
                console.log(arr)
                setLoading(false);
                localStorage.setItem('moduleIcons', JSON.stringify(moduleIcons));
            }
            setLoading(false);
        } catch (error) {
            console.log(error);
        }
    }

    useEffect(() => {
        queryModel();
    }, [])

    const onChangeView = (node, flag) => {
        const newTreeData = JSON.parse(JSON.stringify(treeData));
        let resetChild = false;
        const keys = [];
        const treeDataIteration = (data, isLeaf) => {
            data.map(item => {
                if(item.key == node.key || isLeaf) {
                    item.disabled = flag;
                    resetChild = true;
                } else {
                    resetChild = false;
                }
                if(item.disabled && item.type == "module") keys.push(item.key);
                if(item.children) treeDataIteration(item.children, resetChild);
            })
        };
        treeDataIteration(newTreeData);
        setTreeData(newTreeData);
        if(onView) onView(keys, node);
    }

    const renderTreeNodes = data => 
        data.map(item => {
            if(item.children && item.children.length) { 
                return (
                    <TreeNode 
                        key={item.key}
                        title={renderTitle(item)}
                        disabled={item.disabled}
                    >
                        {renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return (
                <TreeNode 
                    key={item.key}
                    title={renderTitle(item)}
                    disabled={item.disabled}
                />
            );
    });

    return (
        <div className="tree-box">
            {loading ? <Spin className="module-tree-spin"/>:
            treeData.length ? 
                <Tree
                    className="module-view-tree all-module"
                    showLine
                    showIcon
                    showLeafIcon={false}
                    defaultExpandedKeys={['all']}
                >
                    {renderTreeNodes(treeData)}
                </Tree>
                : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            }
        </div>
    )
}

export default ModelTree;
